import { ref, computed, onMounted, onUnmounted, h } from "vue";
import { message } from "@/utils/message";
import { useBreakpointQuery } from "@/utils/device";
import {
  listTradeApps,
  removeTradeApp,
  createTradeApp,
  upgradeTradeApp,
  upgradeAllTradeApps,
  restartTradeApp,
  type TradeAppServiceInfo
} from "@/api/operations";
import type { HttpResponse } from "types/request";
import { ElMessageBox, ElTag, ElButton } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import search from "~icons/ep/search";
import refresh from "~icons/ep/refresh";
import upgrade from "~icons/ep/upload";
import start from "~icons/ep/video-play";
import stop from "~icons/ep/delete";
import restart from "~icons/ep/refresh";

export function useTradeAppOperationsPage() {
  const { isMdUp } = useBreakpointQuery();

  const loading = ref(false);
  const searchValue = ref("");
  const tradeApps = ref<TradeAppServiceInfo[]>([]);
  const refreshInterval = ref<number | null>(null);

  // icons
  const searchIcon = useRenderIcon(search);
  const refreshIcon = useRenderIcon(refresh);
  const upgradeIcon = useRenderIcon(upgrade);
  const startIcon = useRenderIcon(start);
  const stopIcon = useRenderIcon(stop);
  const restartIcon = useRenderIcon(restart);

  const tableSize = computed(() => (isMdUp() ? "default" : "small"));

  const filteredData = computed(() => {
    const q = (searchValue.value || "").toLowerCase();
    if (!q) return tradeApps.value;
    return tradeApps.value.filter(
      app =>
        app.trade_app_name.toLowerCase().includes(q) ||
        app.ctp_settings_name.toLowerCase().includes(q)
    );
  });

  const fetchTradeApps = async () => {
    try {
      loading.value = true;
      const response: HttpResponse<TradeAppServiceInfo[]> =
        await listTradeApps();
      if (response && response.success && response.data) {
        tradeApps.value = response.data;
      }
    } catch (error) {
      message("获取交易APP列表失败", { type: "error" });
      console.error(error);
    } finally {
      loading.value = false;
    }
  };

  const handleRefresh = () => {
    fetchTradeApps();
  };

  const handleUpgradeAll = async () => {
    try {
      loading.value = true;
      await ElMessageBox.confirm("确认升级所有交易APP？", "操作确认", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      });

      const response: HttpResponse<string> = await upgradeAllTradeApps();
      if (response && response.success) {
        message(response.message || "升级操作调用成功", { type: "success" });
        await fetchTradeApps();
      } else {
        const errorMsg = response?.message || "升级操作调用失败";
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      if (error !== "cancel") {
        message("升级操作调用失败", { type: "error" });
        console.error(error);
      }
    } finally {
      loading.value = false;
    }
  };

  const handleStop = async (appName: string) => {
    try {
      loading.value = true;
      await ElMessageBox.confirm(`确认停止 ${appName}？`, "操作确认", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      });

      const response: HttpResponse<string> = await removeTradeApp(appName);
      if (response && response.success) {
        message(`停止${appName}成功`, { type: "success" });
        await fetchTradeApps();
      } else {
        const errorMsg = response?.message || `停止${appName}失败`;
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      if (error !== "cancel") {
        message(`停止${appName}失败`, { type: "error" });
        console.error(error);
      }
    } finally {
      loading.value = false;
    }
  };

  const handleRun = async (appName: string) => {
    try {
      loading.value = true;
      const response: HttpResponse<string> = await createTradeApp(appName);
      if (response && response.success) {
        message(`运行${appName}成功`, { type: "success" });
        await fetchTradeApps();
      } else {
        const errorMsg = response?.message || `运行${appName}失败`;
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      message(`运行${appName}失败`, { type: "error" });
      console.error(error);
    } finally {
      loading.value = false;
    }
  };

  const handleUpgrade = async (appName: string) => {
    try {
      loading.value = true;
      await ElMessageBox.confirm(`确认升级 ${appName}？`, "操作确认", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      });

      const response: HttpResponse<string> = await upgradeTradeApp(appName);
      if (response && response.success) {
        message(`升级${appName}成功`, { type: "success" });
        await fetchTradeApps();
      } else {
        const errorMsg = response?.message || `升级${appName}失败`;
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      if (error !== "cancel") {
        message(`升级${appName}失败`, { type: "error" });
        console.error(error);
      }
    } finally {
      loading.value = false;
    }
  };

  const handleRestart = async (appName: string) => {
    try {
      loading.value = true;
      await ElMessageBox.confirm(`确认重启 ${appName}？`, "操作确认", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      });

      const restartResponse: HttpResponse<string> =
        await restartTradeApp(appName);
      if (restartResponse && restartResponse.success) {
        message(`重启${appName}成功`, { type: "success" });
        await fetchTradeApps();
      } else {
        const errorMsg = restartResponse?.message || `重启${appName}失败`;
        message(errorMsg, { type: "error" });
      }
    } catch (error) {
      if (error !== "cancel") {
        message(`重启${appName}失败`, { type: "error" });
        console.error(error);
      }
    } finally {
      loading.value = false;
    }
  };

  const formatCreatedTime = (dateStr: string): string => {
    if (!dateStr) return "-";
    try {
      const date = new Date(dateStr);
      return date.toLocaleString(undefined, {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false
      });
    } catch {
      return dateStr;
    }
  };

  const isRunning = (app: TradeAppServiceInfo) => {
    return app.service_info && app.service_info.created_at !== "";
  };

  const tableColumns = [
    {
      type: "index",
      label: "#",
      width: 40,
      fixed: "left",
      align: "center",
      className: "text-gray-500 text-xs"
    },
    {
      label: "APP名称",
      prop: "trade_app_name",
      fixed: "left",
      minWidth: 100,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: "CTP设置",
      prop: "ctp_settings_name",
      minWidth: 100,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: "启用状态",
      prop: "enabled",
      width: 90,
      cellRenderer: ({ row }: { row: TradeAppServiceInfo }) =>
        h(
          ElTag,
          {
            type: row.enabled ? "success" : "info"
          },
          () => (row.enabled ? "已启用" : "未启用")
        )
    },
    {
      label: "副本状态",
      prop: "replicas",
      width: 95,
      align: "center",
      cellRenderer: ({ row }: { row: TradeAppServiceInfo }) => {
        if (!row.service_info) {
          return h(ElTag, { type: "danger" }, () => "未创建");
        }

        const replicas = row.service_info.replicas;
        const match = replicas.match(/^(\d+)\/(\d+)$/);
        let type: "success" | "warning" | "info" | "danger" = "info";

        if (match) {
          const [, current, desired] = match;
          const currentNum = parseInt(current);
          const desiredNum = parseInt(desired);

          if (currentNum === desiredNum && currentNum > 0) {
            type = "success";
          } else if (currentNum === 0 && desiredNum === 0) {
            type = "info";
          } else {
            type = "danger";
          }
        }

        return h(ElTag, { type }, () => row.service_info!.replicas);
      }
    },
    {
      label: "运行节点",
      prop: "nodes",
      minWidth: 150,
      cellRenderer: ({ row }: { row: TradeAppServiceInfo }) => {
        if (!row.service_info) {
          return "-";
        }
        return row.service_info.nodes.join(", ");
      }
    },
    {
      label: "创建时间",
      prop: "created",
      width: 180,
      sortable: true,
      cellRenderer: ({ row }: { row: TradeAppServiceInfo }) =>
        row.service_info ? formatCreatedTime(row.service_info.created_at) : "-"
    },
    {
      label: "操作",
      minWidth: 260,
      cellRenderer: ({ row }: { row: TradeAppServiceInfo }) => {
        const running = isRunning(row);
        const buttons: any[] = [];

        if (!running) {
          buttons.push(
            h(
              ElButton,
              {
                type: "primary",
                size: "small",
                onClick: () => handleRun(row.trade_app_name),
                icon: startIcon
              },
              () => "运行"
            )
          );
        }

        if (running) {
          buttons.push(
            h(
              ElButton,
              {
                type: "default",
                size: "small",
                onClick: () => handleUpgrade(row.trade_app_name),
                icon: upgradeIcon
              },
              () => "升级"
            )
          );
        }

        if (running) {
          buttons.push(
            h(
              ElButton,
              {
                type: "warning",
                size: "small",
                onClick: () => handleRestart(row.trade_app_name),
                icon: restartIcon
              },
              () => "重启"
            )
          );
        }

        if (running) {
          buttons.push(
            h(
              ElButton,
              {
                type: "danger",
                size: "small",
                onClick: () => handleStop(row.trade_app_name),
                icon: stopIcon
              },
              () => "停止"
            )
          );
        }

        return h(
          "div",
          {
            style: {
              display: "flex",
              justifyContent: "flex-start",
              gap: "5px"
            }
          },
          buttons
        );
      }
    }
  ];

  onMounted(() => {
    fetchTradeApps();
    refreshInterval.value = window.setInterval(() => {
      if (!loading.value) {
        fetchTradeApps();
      }
    }, 6000);
  });

  onUnmounted(() => {
    if (refreshInterval.value !== null) {
      clearInterval(refreshInterval.value);
      refreshInterval.value = null;
    }
  });

  return {
    // header
    searchValue,
    loading,
    searchIcon,
    refreshIcon,
    upgradeIcon,

    // table
    tableSize,
    filteredData,
    tableColumns,

    // actions
    handleRefresh,
    handleUpgradeAll
  };
}
